<?php
namespace app\msg\controller;

use extra\BusinessException;
use extra\Constant;
use think\Log;
use think\Config;

use app\msg\model\MessageBox as MessageBoxModel;
use app\msg\model\MessageTargetUser as MessageTargetUserModel;
use app\msg\model\MessageHandlingHistory as MessageHandlingHistoryModel;
use app\msg\model\HtmlTemplate  as HtmlTemplateModel;


class MessageBox extends Base {
    private $messageEditingStatus=0;//1:存草稿,2:发布,3:删除Boss编辑用
    private $targetUser=0;//1:所有用户,2:未下单用户,3:还款中用户,4:已逾期用户,5:指定用户)当为5时见message_target_user表关系
    /*
     * 获取单条消息详细内容
     */
    public function update() {
        $request=$this->data['upData'];
        $must_param = [
            "msg_id"           =>'',
            'title'              => '',
            'abstract'           => '',
            'type'               => '',
            'activity_link'      => '',
            'content'            => '',
            'cover_picture_link' => '',
            'target_user'        => '',
            'target_user_id_str' => '',
            'release_type'       => '',
            'release_time'       => '',
            'admin_id'           => '',
            'admin_name'         => '',
            'status'             => '',
        ];
        
        Log::write('MessageBox<>update<>'.$request['msg_id'].':'.file_get_contents("php://input"));
        //参数校验
        paramCheck($request,$must_param);
    
        Log::write('MessageBox<>update<>'.$request['msg_id'].'<>request:'.json_encode($request));
    
        if(!$msgID=(int)$request['msg_id']){
            json(['code'=>Constant::ERROR,'msg'=>'the msgID is err','data'=>[]])->send();
        }
        
        //当target_user为5时候，target_user_id_str才有值。
        $targetUserIdStr = addslashes($request['target_user_id_str']);
        $this->messageEditingStatus=(int)$request['status'];
        $this->targetUser=(int)$request['target_user'];
    
//        //消息作者 创建人ID
        (int)$request['admin_id'] ?
//            $updateData['admin_id'] = (int)$request['admin_id']
            $admin_id = (int)$request['admin_id']
            :
            json(['code'=>Constant::ERROR,'msg'=>'the messsage admin_id is null'])->send();
//
//        //消息作者姓名
        addslashes($request['admin_name']) ?
//            $updateData['admin_name'] = addslashes($request['admin_name'])
            $admin_name = addslashes($request['admin_name'])
            :
            json(['code'=>Constant::ERROR,'msg'=>'the messsage admin_name is null'])->send();//消息作者姓名
    
        //1:存草稿,2:发布,3:删除
        (int)$request['status'] ?
            $updateData['status']=$this->messageEditingStatus
            :
            json(['code'=>Constant::ERROR,'msg'=>'the messsage status is null'])->send();

        $msgConf=Config::get('MESSAGE_CACHE');
        $this->cache_db->set($msgID.'_'.$msgConf['MSG_STATUS_KEY'],$updateData['status'],$msgConf['MSG_STATUS_TIME']);
        
        $messageBoxModel = new MessageBoxModel;
    
        //发布按钮时候
        if($this->messageEditingStatus == $messageBoxModel::MESSAGE_STATUS_OK){
            //消息标题
            $request['title'] ?
                $updateData['title']=addslashes($request['title'])
                :
                json(['code'=>Constant::ERROR,'msg'=>'the messsage title is null'])->send();
            //文章摘要
            $request['abstract'] ?
                $updateData['abstract']=addslashes($request['abstract'])
                :
                json(['code'=>Constant::ERROR,'msg'=>'the messsage abstract is null'])->send();
            //记录分类(1:活动链接,2:推送文章)
            $request['type'] ?
                $updateData['type']=(int)$request['type']
                :
                json(['code'=>Constant::ERROR,'msg'=>'the messsage type is null'])->send();
            //活动链接
            if($request['type']!=2) {
                $request['activity_link']
                    ?
                    $updateData['activity_link'] = addslashes($request['activity_link'])
                    :
                    json(['code' => Constant::ERROR, 'msg' => 'the messsage activity_link is null'])->send();
            }
            //当type为2时，文章内容
            if($request['type']==2){
                $request['content'] ?
                    $content=$request['content']
                    :
                    json(['code'=>Constant::ERROR,'msg'=>'the messsage content is null'])->send();
            }
        
            //1:所有用户,2:未下单用户,3:还款中用户,4:已逾期用户,5:指定用户
            $request['target_user'] ?
                $updateData['target_user'] = $this->targetUser
                :
                json(['code'=>Constant::ERROR,'msg'=>'the messsage target_user is null'])->send();
            //5:指定用户发送消息
            if($this->targetUser == 5){
                //制定用户ID（string类型例如：1,2,3）当target_user为5时候，target_user_id_str才有值。
                $request['target_user_id_str'] ?
                    $targetUserIdStr = addslashes($request['target_user_id_str'])
                    :
                    json(['code'=>Constant::ERROR,'msg'=>'the messsage target_user_id_str is null'])->send();
            }
            //发布类型 1:立即发送 2:定时发送
            (int)$request['release_type'] ?
                $updateData['release_type']=(int)$request['release_type']
                :
                json(['code'=>Constant::ERROR,'msg'=>'the messsage release_type is null'])->send();
            //release_type为发送时间
            $updateData['release_time']=(int)$request['release_time'];
            if($request['status']!=2){
                (int)$request['release_time'] ?
                    $updateData['release_time']=(int)$request['release_time']
                    :
                    json(['code'=>Constant::ERROR,'msg'=>'the messsage release_time is null'])->send();
            }
            
        
        }else{
            $updateData['title']=addslashes($request['title']);
            $updateData['abstract']=addslashes($request['abstract']);
            $updateData['type']=(int)$request['type'];
            $updateData['activity_link']=addslashes($request['activity_link']);
            $updateData['target_user'] = $this->targetUser;
            $targetUserIdStr = addslashes($request['target_user_id_str']);
            $updateData['release_type']=(int)$request['release_type'];
            $updateData['release_time']=(int)$request['release_time'];
            
        }
        $updateData['add_time']=time();
        //封面图片链接
        $updateData['cover_picture_link'] = addslashes($request['cover_picture_link']);//封面图片链接
    
    
        //文章内容处理生成本地文件
        if ($updateData['type']==MessageBoxModel::ARTICLE_TYPE){
            $templateModel=new HtmlTemplateModel;
            $html=$templateModel->template($content,1);
            @file_put_contents(Constant::MSG_HTML_PATH.'/../../public/static/msghtml/'.time().'.html',$html);
            @file_put_contents(Constant::MSG_HTML_PATH.'/../../public/static/msghtml/'.time().'.txt',$content);
            $updateData['html']=Constant::MSG_STATIC_URL.time().'.html';
            $updateData['content']=Constant::MSG_HTML_PATH.'/../../public/static/msghtml/'.time().'.txt';
        }
        
        //更新数据
        $messageBoxModel->updateDataByID($msgID,$updateData);
        
        $essageTargetUserModel=new MessageTargetUserModel;
        $messageBoxData=$messageBoxModel->getOneMessageBoxDataByID($msgID);
        $essageTargetUserModel->deleteMessageTargetUserByMsgID($msgID,$messageBoxData['add_time']);
        //当添加类型为制定用户添加时
        $this->addDataToMessageTargetUser($msgID,$targetUserIdStr);
    
        //添加操作历史记录
        $messageHandlingHistoryModel=new MessageHandlingHistoryModel();
        $messageHandlingHistoryModel->insertOneDataToMessageHandlingHistory(
            [
                'type'=>$updateData['status'],
                'm_b_id'=>$msgID,
                'admin_id'=>$admin_id,
                'admin_name'=>$admin_name,
                'add_time'=>time(),
            ]
        );
        
        json(['code'=>Constant::SUCCESS,'msg'=>'success','data'=>[]])->send();
        
    }
    /*
     * 获取单条消息详细内容
     */
    public function getOneDetail() {
        $request=$this->data;
        $must_param = [
            "msg_id"           =>'',
        ];
        //参数校验
        paramCheck($request,$must_param);
        if(!$msgID=(int)$request['msg_id']){
            json(['code'=>Constant::ERROR,'msg'=>'the msgID is err','data'=>[]])->send();
        }
        $data=[];
        
        $messageBoxModel=new MessageBoxModel;
        $data=$messageBoxModel->getOneMessageBoxDataByID($msgID);
//        $data['content']=$data['content'] ? file_get_contents($data['content']): '';
        
//        $a= $data['content'];
//        $opts = array(
//            'http'=>array(
//                'method'=>'GET',
//                'timeout'=>1, //设置超时，单位是秒，可以试0.1之类的float类型数字
//            )
//        );
//        $context = stream_context_create($opts);
        if($data['content']){
            $data['content']=file_get_contents($data['content']);
        }else{
            $data['content']='';
        }
        //消息操作历史记录
        $messageHandlingHistory=new MessageHandlingHistoryModel;
        //取出历史记录20条
        $list=$messageHandlingHistory->getListByMsgId($msgID,['list_rows'=>'20']);
        $data['handleHistory']=$list;
        $messageTargetUserModel=new  MessageTargetUserModel;
        $targetUserStr=$messageTargetUserModel->getMessageTargetUserByMsgID($msgID);
        $data['targetUserStr']="$targetUserStr";
        json(['code'=>Constant::SUCCESS,'msg'=>'success','data'=>$data])->send();
    }
    
    /*
     * 对外接口(BOSS)删除消息列表信息
     */
    public function updateStatus(){
        $request=$this->data['deteleData'];
        $must_param = [
            "msg_id_string"           =>'',
        ];
        //参数校验
        paramCheck($request,$must_param);
        //删除数据
        $msgIDArr=explode(',',$request['msg_id_string']);
        $messageBoxModel=new MessageBoxModel;
        foreach ($msgIDArr as $v){
            $messageBoxModel->updateStatusByID($v,$messageBoxModel::MESSAGE_STATUS_DELETE);
        }
        json(['code'=>Constant::SUCCESS,'msg'=>'success','data'=>[]])->send();
    }
    
    /*
     * 对外(BOSS)接口获取消息款消息列表
     */
    public function getList(){
        //参数检验
        $request=$this->data['request'];
        $must_param = [
            "page_num"           =>'',// "一页多少条，不传值20条 例如:25",
            "current_page"       =>'',//"当前页",
//            "nextPage"          => '',//"下一页",
//            "lastPage"          =>'',// "上一页",
            "push_category"      => '',//"推送类别(1:活动链接,2:推送文章)",
            "release_start_time"  =>'',// "发布时间 开始时间 时间戳格式",
            "release_end_time"    =>'',// "发布时间 结束时间 时间戳格式",
            "push_title"         =>'',// "推送标题 例如：天神给你送红包了",
            "target_user"        => '',//"目标用户（1:所有用户,2:未下单用户,3:还款中用户,4:已逾期用户,5:指定用户）",
            "status"     => '',//"消息状态（1:存草稿,2:发布）"
        ];
        //参数校验
        paramCheck($request,$must_param);
        //返回数据
        //一页多少条
        $pageNum=(int)$request['page_num'] ? (int)$request['page_num'] : 20;
        //当前页
        $currentPage=(int)$request['current_page'] ? (int)$request['current_page'] : 1;
        //下一页
//        $nextPage=(int)$request['nextPage'] ? (int)$request['nextPage'] : ($currentPage+1);
        //上一页
//        $lastPage=(int)$request['lastPage'] ? (int)$request['lastPage'] : (($currentPage-1) >0 )? ($currentPage-1) : 0;
        $condition=[];
        $condition['status']=['neq',3];
        //推送类别(1:活动链接,2:推送文章)
        (int)$request['push_category'] ? $condition['type'] = (int)$request['push_category'] : '';
        //发布时间 开始时间 时间戳格式
        (int)$request['release_start_time'] ? $condition['release_time'] = ['gt'=>strtotime(date('Ymd',(int)$request['release_start_time']))]: '';
        //发布时间 结束时间 时间戳格式
        (int)$request['release_end_time'] ? $condition['release_time'] = ['lt'=>strtotime(date('Ymd',(int)$request['release_end_time']).' 23:59:59')]: '';
        //推送标题 例如：天神给你送红包了
        $request['push_title'] ? $condition['title'] =['like','%'.addslashes($request['push_title']).'%'] : '';
        //目标用户（1:所有用户,2:未下单用户,3:还款中用户,4:已逾期用户,5:指定用户）
        (int)$request['target_user'] ? $condition['target_user']=(int)$request['target_user'] : '';
        //消息状态（1:存草稿,2:发布）
        (int)$request['status'] ? $condition['status']=(int)$request['status'] : '';
        $messageBoxModel = new MessageBoxModel;
        $list=$messageBoxModel->getMessageBoxList($condition,['list_rows'=>$pageNum,'page'=>$currentPage],['id'=>'desc']);
        json(['code'=>Constant::SUCCESS,'msg'=>'success','data'=>['respose'=>$list,'request'=>$request]])->send();
        
    }
    
    /*
     * 对外 (BOSS)接口添加消息款接口
     */
    public function addOneData() {
       
        if (!isset($this->data['messsage'])) {
            json(['code'=>Constant::ERROR,'msg'=>'the data messsage is not exist'])->send();
        }
        Log::write('MessageBox<>addOneData<>:'.file_get_contents("php://input"));
        
        $request = $this->data['messsage'];
        //参数检验
        $must_param = [
            'title'              => '',
            'abstract'           => '',
            'type'               => '',
            'activity_link'      => '',
            'content'            => '',
            'cover_picture_link' => '',
            'target_user'        => '',
            'target_user_id_str' => '',
            'release_type'       => '',
            'release_time'       => '',
            'admin_id'           => '',
            'admin_name'         => '',
            'status'             => '',
        ];
        //参数校验
        paramCheck($request,$must_param);
        
        //当target_user为5时候，target_user_id_str才有值。
        $targetUserIdStr = addslashes($request['target_user_id_str']);
        $this->messageEditingStatus=(int)$request['status'];
        $this->targetUser=(int)$request['target_user'];
    
        //消息作者 创建人ID
        (int)$request['admin_id'] ?
            $addData['admin_id'] = (int)$request['admin_id']
            :
            json(['code'=>Constant::ERROR,'msg'=>'the messsage admin_id is null'])->send();
    
        //消息作者姓名
        addslashes($request['admin_name']) ?
            $addData['admin_name'] = addslashes($request['admin_name'])
            :
            json(['code'=>Constant::ERROR,'msg'=>'the messsage admin_name is null'])->send();//消息作者姓名
    
        //1:存草稿,2:发布,3:删除
        (int)$request['status'] ?
            $addData['status']=$this->messageEditingStatus
            :
            json(['code'=>Constant::ERROR,'msg'=>'the messsage status is null'])->send();
    
        $messageBoxModel = new MessageBoxModel;
        
        //发布按钮时候
        if($this->messageEditingStatus == $messageBoxModel::MESSAGE_STATUS_OK){
            //消息标题
            $request['title'] ?
                $addData['title']=addslashes($request['title'])
                :
                json(['code'=>Constant::ERROR,'msg'=>'the messsage title is null'])->send();
            //文章摘要
            $request['abstract'] ?
                $addData['abstract']=addslashes($request['abstract'])
                :
                json(['code'=>Constant::ERROR,'msg'=>'the messsage abstract is null'])->send();
            //记录分类(1:活动链接,2:推送文章)
            $request['type'] ?
                $addData['type']=(int)$request['type']
                :
                json(['code'=>Constant::ERROR,'msg'=>'the messsage type is null'])->send();
            if($request['type']!=2){
                //活动链接
                $request['activity_link'] ?
                    $addData['activity_link']=addslashes($request['activity_link'])
                    :
                    json(['code'=>Constant::ERROR,'msg'=>'the messsage activity_link is null'])->send();
            }
            
            //当type为2时，文章内容
            if($request['type']==MessageBoxModel::ARTICLE_TYPE){
                    $request['content'] ?
                        $content=$request['content']
                        :
                        json(['code'=>Constant::ERROR,'msg'=>'the messsage content is null'])->send();
            }
                
            //1:所有用户,2:未下单用户,3:还款中用户,4:已逾期用户,5:指定用户
            $request['target_user'] ?
                $addData['target_user'] = $this->targetUser
                :
                json(['code'=>Constant::ERROR,'msg'=>'the messsage target_user is null'])->send();
            //5:指定用户发送消息
            if($this->targetUser == 5){
                //制定用户ID（string类型例如：1,2,3）当target_user为5时候，target_user_id_str才有值。
                $request['target_user_id_str'] ?
                    $targetUserIdStr = addslashes($request['target_user_id_str'])
                    :
                    json(['code'=>Constant::ERROR,'msg'=>'the messsage target_user_id_str is null'])->send();
            }
            //发布类型 1:立即发送 2:定时发送
            (int)$request['release_type'] ?
                $addData['release_type']=(int)$request['release_type']
                :
                json(['code'=>Constant::ERROR,'msg'=>'the messsage release_type is null'])->send();
            //release_type为发送时间
            (int)$request['release_time'] ?
                $addData['release_time']=(int)$request['release_time']
                :
                json(['code'=>Constant::ERROR,'msg'=>'the messsage release_time is null'])->send();
           
        }else{
            $addData['title']=addslashes($request['title']);
            $addData['abstract']=addslashes($request['abstract']);
            $addData['type']=(int)$request['type'];
            $addData['activity_link']=addslashes($request['activity_link']);
            $addData['target_user'] = $this->targetUser;
            $targetUserIdStr = addslashes($request['target_user_id_str']);
            $addData['release_type']=(int)$request['release_type'];
            $addData['release_time']=(int)$request['release_time'];
            $content=$request['content'];
        }
        
        //封面图片链接
        $addData['cover_picture_link'] = addslashes($request['cover_picture_link']);//封面图片链接
        //添加时间
        $addData['add_time']=time();
    
        //文章内容处理生成本地文件
        if ($addData['type']==MessageBoxModel::ARTICLE_TYPE){
            $templateModel=new HtmlTemplateModel;
            $html=$templateModel->template($content,1);
            @file_put_contents(Constant::MSG_HTML_PATH.'/../../public/static/msghtml/'.time().'.html',$html);
            @file_put_contents(Constant::MSG_HTML_PATH.'/../../public/static/msghtml/'.time().'.txt',$content);
            $addData['html']=Constant::MSG_STATIC_URL.time().'.html';
            $addData['content']=Constant::MSG_HTML_PATH.'/../../public/static/msghtml/'.time().'.txt';
        }
        
            
        //记录入库
        $messageBoxInsertID=$messageBoxModel->insertMessageBox($addData);
        //当添加类型为制定用户添加时
        $this->addDataToMessageTargetUser($messageBoxInsertID,$targetUserIdStr);
        
        
        //添加操作历史记录
        $messageHandlingHistoryModel=new MessageHandlingHistoryModel();
        $messageHandlingHistoryModel->insertOneDataToMessageHandlingHistory(
            [
                'type'=>$addData['status'],
                'm_b_id'=>$messageBoxInsertID,
                'admin_id'=>$addData['admin_id'],
                'admin_name'=>$addData['admin_name'],
                'add_time'=>time(),
            ]
        );
        
        json(['code'=>Constant::SUCCESS,'msg'=>'success','data'=>[]])->send();
    }
    
    
    /*
     * 添加记录到message_target_user
     */
    private function addDataToMessageTargetUser($messageBoxInsertID,$targetUserIdStr){
        if(!(int)$messageBoxInsertID) return false;
        $messageTargetUserModel=new MessageTargetUserModel;
        
        //当添加类型为立即发布,并且目标用户为指定用户天时
        if(/*$this->messageEditingStatus == MessageBoxModel::MESSAGE_STATUS_OK &&*/ $this->targetUser==5){
            $targetUserIdArr=explode(',',$targetUserIdStr);
            if(!is_array($targetUserIdArr)){
                json(['code'=>Constant::ERROR,'msg'=>'the messsage target_user_id_str is err'])->send();
            }
            $addData=[];
            foreach ($targetUserIdArr as $k => $v){
                $addData[$k]['m_b_id']=$messageBoxInsertID;
                $addData[$k]['customer_id']=(int)$v;
                $addData[$k]['add_time']=time();
            }
            
            return $messageTargetUserModel->insertManyData($addData);
        }
    }
    
    
}


















